// index.js
Page({
	data: {
		question: '',
		messages: [], // 改为消息数组
		isLoading: false,
		scrollTop: 0
	},
	onLoad(e) {
		const storedCookies = wx.getStorageSync('cookies');
		if (storedCookies) {
			getApp().globalData.cookies = storedCookies;
		}
	},
	saveCookies() {
		wx.setStorage({
			key: 'cookies',
			data: getApp().globalData.cookies,
			fail: () => console.warn('Cookie 存储失败')
		});
	},
	onHide() {
		// 每次更新后保存（需节流处理）
		this.saveCookies()
	},
	onInput(e) {
		this.setData({
			question: e.detail.value
		});
	},

	getAnswer() {
		const that = this;
		const question = this.data.question.trim();

		if (!question) {
			wx.showToast({
				title: '请输入问题',
				icon: 'none'
			});
			return;
		}

		// 添加用户消息
		let newMessages = [
			...this.data.messages,
			{
				role: 'user',
				content: question
			}
		]
		console.log('newMessages=', JSON.parse(JSON.stringify(newMessages)))
		newMessages.forEach(v=>delete v.reasoning_content)
		let l=this.data.messages.length
		this.setData({
			isLoading: true,
			[`messages[${l}]`]: {
				role: 'user',
				content: question
			},
			// messages: newMessages,
			question: '' // 清空输入框
		});
		// console.log('newMessages=', newMessages)
		wx.request({
			url: 'https://api.deepseek.com/v1/chat/completions',
			method: 'POST',
			header: {
				'Content-Type': 'application/json',
				'Authorization': 'Bearer sk-547e4f5686be4f1dad53ddff6113ed75',
				'Cookie': getApp().getCookieHeader() // 携带历史 Cookie
			},
			data: {
				model: "deepseek-reasoner",//"deepseek-chat", // deepseek-reasoner
				messages: newMessages // 发送完整对话历史
			},
			success(res) {
				console.log(res)
				getApp().syncCookies(res); // 同步新 Cookie
				if (res.statusCode === 200 && res.data.choices?.[0]?.message) {
					let response = res.data.choices[0].message
					// delete response.reasoning_content
					that.setData({
						[`messages[${l+1}]`]: response,
						// messages: [...newMessages, response],
						scrollTop: 99999 // 自动滚动到底部
					});
				} else {
					that.showError('获取答案失败');
				}
			},
			fail() {
				that.showError('请求失败');
				that.setData({
					messages: that.data.messages.slice(0, -1)
				}); // 回滚无效提问
			},
			complete() {
				that.setData({
					isLoading: false
				});
			}
		});
	},

	showError(msg) {
		wx.showToast({
			title: msg,
			icon: 'none'
		});
	}
});